#include <iostream>
#include <unistd.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
using namespace std;
void Childewritr(int fd)
{
    int cnt = 0;
    while (1)
    {
        char buffer[1024];
        buffer[0] = 0;
        snprintf(buffer,sizeof(buffer),"child: pid=%d cnt=%d\n",getpid(),cnt++);
        write(fd, buffer, strlen(buffer));       
        cout<<"child: "<<cnt<<endl;
        sleep(1);
       // break;
    }
}    
void Fatheread(int fd)
{
    while (1)
    {
        //sleep(5);
        char buffer[1024];
        buffer[0] = 0;
        size_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "father: " << buffer << endl;
        }
        else
        {
            cout<<"n:"<<n<<endl;
            cout<<"chuld process has exited"<<endl;
            break;
        } 
        break; 
     }
}
    int main()
    {
        // cout<<"Hello World"<<endl;
        // 创建管道
        int fds[2];
        int n = pipe(fds);
        if (n < 0)
        {
            cerr << "Pipe creation failed" << endl;
            return 1;
        }
        // cout << "fds[0] = " << fds[0] << endl;
        // cout << "fds[1] = " << fds[1] << endl;
        // 创建子进程
        int pid = fork();
        if (pid < 0)
        {
            cerr << "Fork failed" << endl;
            return 1;
        }
        else if (pid == 0)
        {
            close(fds[0]);

            Childewritr(fds[1]); // 写端
            close(fds[1]);       // 关闭写端
            exit(0);
        }
        
    
        close(fds[1]); // 关闭写端
        Fatheread(fds[0]); // 读端
        close(fds[0]); // 关闭读端
        int staus=0;
        waitpid(pid, &staus, 0);
        printf("child process exit status: %d\n signal: %d\n ", staus>>8&0xff, staus&0xff);
        return 0;
    }

    //父子进程通信时看到同一块内存资源是什么

    //正常的管道文件，自带同步机制，父子进程之间数据交换，父进程先写，子进程再读。
    
    //管道面向字节流，数据以字节序列的形式在管道中传输，每个字节都有唯一的编号，编号从0开始。

    //管道的通信属于半双工通信，即只能单向传输数据，不能双向交流。

